<script lang="ts" setup>
import { approveOrderAppeal } from '@/api/expense'
import { queryShortTermDetail } from '@/api/order'
import { queryShortTermDetailResponseData } from '@/api/order/types/order'
import { getToken } from '@/utils/cache/cookies'
import { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import { computed, reactive, ref } from 'vue'
const dialogVisible = ref<boolean>(false)
const form = reactive({
  applyAmount: 0,
  amount: 0,
  type: true,
  orderAppealId: 0,
  status: '1',
  orderId: ''
})
const emits = defineEmits(['refresh'])
const data = ref<queryShortTermDetailResponseData | null>(null)
const disabled = ref<boolean>(true)
const formRef = ref<FormInstance | null>(null)
const getInfo = async () => {
  try {
    const res = await queryShortTermDetail({
      token: getToken() ?? '',
      orderId: form.orderId
    })
    if (res.statusCode === '0') {
      data.value = res.data
    }
  } catch (error) {
    console.error(error)
  }
}
const reset = () => {
  formRef.value?.resetFields()
}
const submit = () => {
  formRef.value?.validate(async (valid) => {
    try {
      const res = await approveOrderAppeal({
        token: getToken() ?? '',
        orderAppealId: form.orderAppealId,
        resolution: '',
        status: form.status as '0' | '1',
        amount: form.amount
      })
      if (res.statusCode === '0') {
        ElMessage.success(res.data)
        dialogVisible.value = false
        emits('refresh')
      }
    } catch (error) {
      console.error(error)
    }
  })
}

const setData = (amount: number, id: number, status: '0' | '1', orderId: string) => {
  form.applyAmount = amount
  form.amount = form.applyAmount
  form.orderAppealId = id
  form.status = status
  form.orderId = orderId
  getInfo()
}
const open = () => {
  dialogVisible.value = true
}
defineExpose({ open, setData })

const handleChangeType = () => {
  if (form.type) {
    form.amount = form.applyAmount
    disabled.value = true
  } else {
    disabled.value = false
  }
}
</script>

<template>
  <el-dialog title="退款金额" v-model="dialogVisible" center width="550px">
    <el-form :model="form" ref="formRef" label-width="130px">
      <el-form-item prop="applyAmount" label="申请退款金额：">
        <el-input v-model="form.applyAmount" :disabled="true" />
      </el-form-item>
      <el-form-item prop="type" label="退款选择：">
        <el-radio-group v-model="form.type" @change="handleChangeType">
          <el-radio label="全额退款" :value="true" />
          <el-radio label="部分退款" :value="false" />
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="amount" label="退款金额：">
        <el-input v-model="form.amount" :disabled="disabled" placeholder="请输入退款金额" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="reset">取消</el-button>
      <el-button type="primary" @click="submit">确定</el-button>
    </template>
  </el-dialog>
</template>

<style scoped></style>
